import router from "@/router";
import { useUserStore } from "@/store/modules/user";
import { useVariableStore } from "@/store/modules/variable";
import { usePrintStore } from "@/store/modules/print"
import { cardEject } from "./kiosk";
import { clearStorage, removeStorage } from './localStorage';
import { defineComponent, h, VNode } from "vue";
import { useDeviceStore } from "@/store/modules/device";
import { IS_DEV ,MOCK_SWIPE} from "@/config";
import { useConfigStore } from "@/store/modules/config";
// 从当前浏览器地址栏中获取base url
export function getCurrentUrl() {
    return window.location.protocol + "//" + window.location.host
}

// "true" | "True" 转 true
export function strToBool(str: string | boolean): boolean {
    if (str && typeof (str) === 'string') {
        return str.toLowerCase() === 'true'
    } else {
        return str as boolean
    }
}

// 获取浏览器地址栏参数
export function getUrlKey(name: string) {
    let [, param] = window.location.search.split("?")
    return paramToObj(param || '')[name];
}

/** 判断空对象 */
export function notNullObj(obj: object) {
    return JSON.stringify(obj) !== "{}"
}

/**
 * {a:1,b:2} 转成 a=1&b=2
 * @param {Object} json
 * @returns {Array}
 */
export function param(json: any) {
    if (!json) return ''
    return Object.keys(json).map(key => {
        if (json[key] === undefined) return ''
        return key + '=' + json[key]
    }).join('&')
}

/**
* a=1&b=2 转成 { a:1,b:2 }
* @param {Object} json
* @returns {Array}
*/
export function paramToObj(param: string) {

    if (!param) {
        return {}
    }
    const obj: any = {}
    const searchArr = param.split('&')
    searchArr.forEach(v => {
        const index = v.indexOf('=')
        if (index !== -1) {
            const name = v.substring(0, index)
            const val = v.substring(index + 1, v.length)
            obj[name] = val
        }
    })
    return obj
}

/**
 * 格式化日期 返回年月日时分秒
 * @param date 日期
 * @returns
 */
export function fmtTime(date: any) {
    if (!verifyDate(date)) return ""
    if (!(date instanceof Date)) {
        if ((date + "").includes("Date")) {
            date = new Date(parseInt(date.replace("/Date(", "").replace(")/", "")));
        } else {
            date = new Date(date)
        }
    }
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = (n: any) => {
    n = n.toString()
    return n[1] ? n : `0${n}`
}

/**
 * 格式化日期-精确到天
 * @param {时间} date
 */
export function fmtDate(date: any) {
    if (!verifyDate(date)) return ""
    if (!(date instanceof Date)) {
        if ((date + "").includes("Date")) {
            date = new Date(parseInt(date.replace("/Date(", "").replace(")/", "")));
        } else {
            date = new Date(date)
        }
    }
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${[year, month, day].map(formatNumber).join('-')}`
}

/**
 * 格式化日期-精确到天-返回几月几日
 * @param {时间} date
 */
export function fmtDateStr(date: any) {
    if (!verifyDate(date)) return ""
    if (!(date instanceof Date)) {
        if ((date + "").includes("Date")) {
            date = new Date(parseInt(date.replace("/Date(", "").replace(")/", "")));
        } else {
            date = new Date(date)
        }
    }
    const month = date.getMonth() + 1
    const day = date.getDate()
    return month + "月" + day + "日"
}

/**
 * 获取未来多少天日期的数组(不包括今天)
 * @param {天数} num
 */
export function getDateList(num: any) {
    let toDay = null
    let list = []
    for (var i = 0; i < num; i++) {
        toDay = new Date
        list.push(fmtDate(toDay.setDate(toDay.getDate() + (i + 1))))
    }
    return list
}

/**
 * 格式化日期-只保留到时分秒
 * @param {时间} date
 */
export function fmtTime2(date: any) {
    if (!verifyDate(date)) return ""
    if (!(date instanceof Date)) {
        if ((date + "").includes("Date")) {
            date = new Date(parseInt(date.replace("/Date(", "").replace(")/", "")));
        } else {
            date = new Date(date)
        }
    }
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return `${[hour, minute, second].map(formatNumber).join(':')}`
}

// 验证日期date格式
function verifyDate(date: any) {
    if (!date == true) {
        return false
    }
    return true
}

// 获取当前周几
function getWeekDate(date: any) {
    var now = date;
    var day = now.getDay();
    var weeks = new Array(
        "周日",
        "周一",
        "周二",
        "周三",
        "周四",
        "周五",
        "周六"
    );
    var week = weeks[day];
    return week;
}

/** 获取今天日期数据 */
export function getToday() {
    let date = new Date()
    return {
        date: fmtDateStr(date),
        week: getWeekDate(date)
    }
}

/** 回到首页 */
export function backToHome() {
    showLoading()
    const userStore = useUserStore()
    const configStore = useConfigStore();
    if (IS_DEV) {
        removeStorage("dev_user_data")
        removeStorage("dev_card_info_data")
    }
    // removeStorage("temp_route")
    try {
        cardEject()
        _exit()
    } catch (error) {
        _exit()
    }

    function _exit() {
        if(MOCK_SWIPE){
            clearStorage()
        }

        console.log("执行_exit");
        // 在首页则清除用户
        if (router.currentRoute.value.name == "HomePage"
        || router.currentRoute.value.name == "independentCheckIn"
        ) {
            if (userStore.user) {
                userStore.clear()
            }
            closeLoading();
        } else {
            // 不在首页需要回到首页再清用户
            showLoading();
            userStore.clear()
            if(configStore.indexPage==null){
              router.replace("/")
            }else{
              router.replace(configStore.indexPage)
            }
            closeLoading();
        }


    }
}

/** 忽略中间数字123456789 -> 123**6789 （只处理长度大于7的内容） */
export function ignore(num: number | string): string {
    num = "" + num
    let strArr = num.split("")
    let length = strArr.length

    if (length <= 7) {
        return num
    }

    strArr.forEach((e, index) => {
        if (![0, 1, 2, length - 1, length - 2, length - 3, length - 4].includes(index)) {
            strArr[index] = "*"
        }
    })

    return strArr.join("")
}

// 显示加载
export function showLoading(title: string = "系统处理中，请稍后！") {
    const variableStore = useVariableStore()
    variableStore.showLoading(title)
}

// 关闭加载
export function closeLoading() {
    const variableStore = useVariableStore()
    variableStore.closeLoading()
}

// 16位转rgb
export function set16ToRgb(str: any, type: "str" | "list"): any {
    var reg = /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/
    if (!reg.test(str)) { return ""; }
    let newStr = (str.toLowerCase()).replace(/\#/g, '')
    let len = newStr.length;
    if (len == 3) {
        let t = ''
        for (var i = 0; i < len; i++) {
            t += newStr.slice(i, i + 1).concat(newStr.slice(i, i + 1))
        }
        newStr = t
    }
    let arr = []; //将字符串分隔，两个两个的分隔
    for (var i = 0; i < 6; i = i + 2) {
        let s = newStr.slice(i, i + 2)
        arr.push(parseInt("0x" + s))
    }
    if (type === "str") {
        return 'rgb(' + arr.join(",") + ')';
    } else if (type === "list") {
        return arr
    }
}

// rgb转16位
export function setRgbTo16(str: any) {
    let reg = /^(rgb|RGB)/;
    if (!reg.test(str)) { return; }
    var arr = str.slice(4, str.length - 1).split(",")
    let color = '#';
    for (var i = 0; i < arr.length; i++) {
        var t = Number(arr[i]).toString(16)
        if (t == "0") {   //如果为“0”的话，需要补0操作,否则只有5位数
            t = t + "0"
        }
        color += t;
    }
    return color;
}

/** 通过路由名称获取对应keepAlive数组 解析格式 reserve-step2 => ["reserve-step1","reserve-step2"]  */
export function getStepList(routerName: string): string[] {
    if (!routerName.includes("-")) {
        return []
    }

    const arr = routerName.split("-")

    const num = parseInt(arr[1].split("step")[1])

    let retArr = []
    for (let i = 0; i < num; i++) {
        retArr.push(arr[0] + "-step" + (i + 1))
    }

    return retArr
}

/**
 * 路由数组解析数组
 * theDayReserve-xzks  => ["theDayReserve-xzks"]
 * @param routerName
 * @returns
 */
export function getKeepAliveStep(routers: any[], routerName: string): string[] {
    let strList: string[] = []
    routers.some((e) => {
        strList.push(e.name)
        return routerName === e.name
    })


    return strList
}

/** 重置当前页倒计时 */
export function resetTime(time?: number) {
    const variableStore = useVariableStore()
    variableStore.resetTime(time)
}

/** 延迟执行 */
export function delayTimeout(time: number = 2000) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(true)
        }, time)
    })
}

/** 显示打印中 */
export function showPrint() {
    const printStore = usePrintStore();
    printStore.showPrint()
}

/** 关闭打印中 */
export function closePrint() {
    const printStore = usePrintStore();
    printStore.closePrint()
}

// jyjc.jc_list
export function resolvePath(path: string) {
    const pathList = path.split(".")

    return getCurrentUrl() + "/ldzzj/ldzzj/page/" + pathList.join("/")

}

/**
 * tsx类型文件转为vue组件
 * @param vNode tsx元素
 * @returns vue组件
 */
export function tsxToVueComponent<T>(vNode: (props: T) => VNode): () => JSX.Element {
    const ret: any = h(defineComponent({
        render: vNode
    }))
    return ret
}

/** 是否显示为1080分辨率 */
export function is1080(): boolean {
    const width: number = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    // if(window.screen.width>window.screen.height){
    //   return false;
    // }
    if (width <= 1080) {
        if(window.screen.width*1.0/window.screen.height<=0.6){
          return true
        }
    }
    return false
}


interface IWeekRetutn{
    /** 星期几 */
    week:string;
    /** 年月日 */
    date:string;
    /** 几月几日 */
    day:string;
}

/** 获取未来七天数据 */
export function getFutureWeek() :IWeekRetutn[]{
    let weekList = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']

    let day:IWeekRetutn[] = []

    for(var i = 0; i < 14; i++) {
		var dayTime = new Date();
		dayTime.setDate(dayTime.getDate() + i);

        day.push({
            week:weekList[dayTime.getDay()],
            date:fmtDate(dayTime),
            day:fmtDateStr(dayTime),
        })
	}

    return day
}

export function is1024(){
  if(getPageZoom()<0.95){
    return true;
  }
  return false;
}

export function getPageZoom() {
  const width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  const zoom = window.screen.availWidth/width;
  return zoom;
}
(window as any).getPageZoom=getPageZoom;
